package FlowGram.Application.User;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

/**
 * This class handles the creation of the user objects
 * 
 * @author Owner
 *
 */
public class UserManager {

	/**
	 * This is the user that is current logged into 
	 * the application. 
	 */
	public User currentUser; 
	/**
	 * This is the file that this 
	 * class will read in order to get information. 
	 */
	private String currentFile; 
	
	
	/**
	 * When you create an instance of the UserManager class you 
	 * have to pass in the userFile.  This will enable the UserManager
	 * to actually manage the list of the users. 
	 * @param file
	 */
	
	// TODO Do I really need to pass in the file won't 
	// there be a specified that contains all the users

	
	/**
	 * This method will read the file and determine whether a user is 
	 * can be logged into the system.  If they can be this method will change
	 * the current user to the found and return true.  If they can not be found this 
	 * method will return false.  
	 * @param username
	 * @param password
	 * @return
	 * @throws IOException 
	 */
	boolean login(String username, String password) throws IOException{
		BufferedReader read = null; 
        read = new BufferedReader(new FileReader("UserFile"));
        String line = null;
		try {
			line = read.readLine();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
        while(line != null){
        	 Scanner firstline = new Scanner(line); 
             String  firstword = firstline.next();
             String passcode = firstline.next();
             if(username.equals(firstword)&& passcode.equals(password))
	         {
	          // Then here I will create the new user object
              //TODO: Make sure this prints out the correct values 
              // Add some parameter to handle the whole level thing 
                 String datestamp = firstline.next();
                 int numberLevel = Integer.parseInt(firstline.next()); 
                 String path = firstline.next(); 
            	 User present = new User(firstword,passcode,datestamp,numberLevel,path); 
            	 currentUser = present; 
            	return true; 
	         }
	         else{
	        	 line = read.readLine();
	         }
        }
        read.close(); 
		return false;  
	}
	
	public User getCurrentUser() {
		return currentUser;
	} 

	/**
	 * This method will read the file to determine if the 
	 * user exists within the file. 
	 * @param name
	 * @return
	 * @throws IOException 
	 */
	boolean UserNameExists(String name) throws IOException{
		BufferedReader read = null; 
        read = new BufferedReader(new FileReader("UserFile"));
        String line = null; 
		try {
			line = read.readLine();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
        while(line != null){
        	 Scanner firstline = new Scanner(line); 
             String  firstword = firstline.next();
             if(name.equalsIgnoreCase(firstword))
	         {
	        	 return true; 
	         }
	         else{
	        	 line = read.readLine();
	         }
        }
        read.close(); 
		return false; 
	}
	
	/**
	 * This method will delete a user
	 * @param userName
	 * @return
	 *In this method I will have to create a temporary file 
	 *then write to the temporary file all the lines except that I wish to remove. 
	 *Then change the name of the temporary file the original file name. 
	 *You also have to delete the directly for the user that may or may not have been created
	 *LINE.startsWith(username) you know to skip that line. 
	 * @throws IOException 
	 */
	boolean remove(String userName) throws IOException{
		// This is the file the you will read from to delete. 
			if(UserNameExists(userName)!= true){
				System.out.println("Can not remove a user that does not exits"); 
				return false; 
			}
		
				File start = new File("UserFile");
				
				// create the temp file
				 File tempFile = new File(start.getAbsolutePath() + ".tmp");
				
				    BufferedReader read = new BufferedReader(new FileReader(start));
				    BufferedWriter ecrie = new BufferedWriter(new FileWriter(tempFile)); 
			        String line = null;
			        line = read.readLine();
			       while(line != null){   
			    	   
			    	   if(line.startsWith(userName))
			    	   {
			    		   // I want to skip it and read the next line
			    		   line = read.readLine(); 
			    	   }
			    	   else if(line != null)
			    	   {
			    		   
			    		   ecrie.write(line); 
			    		   line = read.readLine(); 
			    	   }
			       }
			       read.close();
			      ecrie.close(); 
			   // then here i delete the old file and 
			   // rename the temporary file the name of the input file 
			       start.delete(); 
			       tempFile.renameTo(start);  
				
		return true; 
	}
	
	/**
	 * This method will be used to create a User
	 * and add it to the User database. 
	 * Also you have to create a in folder in the workspace
	 * C:\\Workspaceusername\project\class\  create all folders that will be populated later. 
	 *Shall we create something else to make it possible to chose the directory to store.
	 * @param name
	 * @param password
	 * @return
	 * @throws IOException  
	 */
	boolean Add (User username) throws IOException{
		
		File start = new File("UserFile");
		
	    BufferedWriter ecrie = new BufferedWriter(new FileWriter(start, true));
	   String space = " "; 
	    
       ecrie.write(username.getUserName());
       ecrie.write(space); 
       ecrie.write(username.getPassword());
       ecrie.write(space); 
       ecrie.write(username.getLastLogin());
       ecrie.write(space); 
       ecrie.write(username.getLevel());
       ecrie.write(space); 
       ecrie.write(username.getWorkspace()); 
       ecrie.write(space); 
       ecrie.write('\n'); 
      ecrie.close();
      
      return true; 
	}
	
	/**
	 * This method will create a User Profile for the 
	 * first user of the system. 
	 * 
	 * @param username
	 * @param password
	 * @param password
	 * @return
	 * @throws IOException 
	 */
	boolean CreateUser(String username, String password, String path) throws IOException{
		// Using the string path I have create the directory where 
		// I instantiate all files for the user 
		// once they pick a directory
		File dir = new File (path +"/" + username + "project");
		//File nouv = new File(path, username);
		dir.mkdir(); 
	
		User nouveauUser = new User(username, password, "date", 0, path); 
		return true;
	}
	/**
	 * Before you log out you have to update any changes to the User profile
	 * What will also change is the date the represent the last time the user
	 * logged in. 
	 * What is the user closes with out logging out this method should still be called.
	 * @return
	 *update(User user)
	 * @throws IOException 
	 */
	boolean SaveUser(User user) throws IOException{
		Date myDate = new Date(); 
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd:HH-mm-ss"); 
		String monDate = sdf.format(myDate);
		user.setLastLogin(monDate); 
		if(UserNameExists(user.getUserName()))
		{
			// If the user already exists then remove that user from the file 
			remove(user.getUserName());
		}
		// Add the user to file 
		Add(user); 
		return true;
	}
	/**
	 * Est-ce que necessaire? 
	 * @param user
	 * @return
	 */
	boolean changePassword(User user){
		return true; 
	}
}
  